import re
import sys
import os
import os.path
import argparse

from.docxfile import DocxFile, DocxFileError
from.converter import Converter
from.docxmedia import DocxMedia
from.secondChange import convert_docx_md   # 导入二次转换功能

PROG = "docx2md"
import docx2md

VERSION = f"{PROG} {docx2md.__version__}"


def main():
    args = parse_args()
    if args.all:
        process_all_docx_files(args)
    else:
        process_single_file(args)


def parse_args():
    USAGE = """python -m docx2md [-h] [-m] [-v] [--debug] [--all] [SRC.docx]"""
    parser = argparse.ArgumentParser(prog=PROG, usage=USAGE,
                                     description="Convert DOCX files to Markdown with image extraction.")
    parser.add_argument("src", metavar="SRC.docx", nargs='?',
                        help="Microsoft Word file to read. If not provided and --all is used, all.docx files in current directory will be processed.")
    parser.add_argument(
        "-m",
        "--md_table",
        action="store_true",
        help="use Markdown table notation instead of <table>",
        default=False,
    )
    parser.add_argument(
        "-v",
        "--version",
        help="show version",
        action="version",
        version=VERSION,
    )
    parser.add_argument("--debug", help="for debug", action="store_true", default=False)
    parser.add_argument("--all", help="process all.docx files in current directory", action="store_true",
                        default=False)
    return parser.parse_args()


def create_docx(file):
    try:
        return DocxFile(file)
    except Exception as e:
        print(f"Error opening {file}: {e}")
        exit(1)


def check_and_create_dir(dir_path):
    if not os.path.isdir(dir_path):
        if os.path.exists(dir_path):
            print(f"Cannot create directory {dir_path} because a file with the same name exists.")
            exit(1)
        os.makedirs(dir_path)


def save_keyfile(docx, target_dir):
    def save_xml(file, text):
        print(f"# save {file}")
        with open(file, "wb") as f:
            f.write(text)

    save_xml(os.path.join(target_dir, "document.xml"), docx.document())
    save_xml(os.path.join(target_dir, "document.xml.rels"), docx.rels())


def convert_docx_to_md(docx, media, use_md_table):
    xml_text = docx.document()
    converter = Converter(xml_text, media, use_md_table)
    # 提取链接并进行处理
    links = extract_links(xml_text)
    md_text = converter.convert()
    for link in links:
        md_text = md_text.replace(link, convert_link_to_markdown(link))
    return md_text


def extract_links(xml_text):
    # 使用正则表达式或其他方法提取文档中的链接
    link_pattern = r'<a href="(.*?)">(.*?)</a>'
    # 将 xml_text 转换为字符串类型
    if isinstance(xml_text, bytes):
        xml_text = xml_text.decode('utf-8')
    links = re.findall(link_pattern, xml_text)
    return [link[0] for link in links]

def convert_link_to_markdown(link):
    # 将链接转换为 Markdown 格式，例如 [链接描述](链接地址)
    return f"[链接描述]({link})"


def save_md(file, text):
    print(f"# save {file}")
    with open(file, "w", encoding="utf-8") as f:
        f.write(text)


def process_single_file(args, file_path=None):
    if file_path:
        src = file_path
    else:
        src = args.src

    if not src:
        print("No source file specified.")
        exit(1)

    if not src.endswith(".docx"):
        print(f"File {src} is not a.docx file.")
        exit(1)

    base_name = os.path.splitext(os.path.basename(src))[0]
    target_md = f"{base_name}.md"
    target_folder = os.path.join(os.path.dirname(src), base_name)
    images_folder = os.path.join(target_folder, f"{base_name}")

    check_and_create_dir(target_folder)
    check_and_create_dir(images_folder)

    docx = create_docx(src)
    media = DocxMedia(docx)
    if args.debug:
        save_keyfile(docx, target_folder)
    md_text = convert_docx_to_md(docx, media, args.md_table)

    md_path = os.path.join(target_folder, target_md)
    save_md(md_path, md_text)

    media.save(images_folder)

    print(f"Processed {src} -> {md_path}")
    print(f"Images saved to {images_folder}")

    perform_second_conversion(md_path)


def perform_second_conversion(md_path):
    original_md_path = md_path
    converted_md_path = os.path.join(os.path.dirname(md_path), f"converted_{os.path.basename(md_path)}")

    with open(original_md_path, 'r', encoding='utf-8') as file:
        md_text = file.read()

    converted_md_text = convert_docx_md(md_text)
    converted_md_text = replace_image_paths(converted_md_text, md_path)

    with open(converted_md_path, 'w', encoding='utf-8') as file:
        file.write(converted_md_text)

    old_md_path = os.path.join(os.path.dirname(original_md_path), f"old_{os.path.basename(original_md_path)}")

    if os.path.exists(old_md_path):
        os.remove(old_md_path)

    os.rename(original_md_path, old_md_path)

    if os.path.exists(original_md_path):
        os.remove(original_md_path)

    os.rename(converted_md_path, original_md_path)

    print(
        f"Second conversion complete. Original file renamed to {old_md_path}, and new markdown file saved as {original_md_path}")


def replace_image_paths(md_text, md_path):
    base_name = os.path.splitext(os.path.basename(md_path))[0]
    images_folder = f"{base_name}"
    def replace_img_src(match):
        src = match.group(1)
        if src.startswith("media/"):
            new_src = src.replace("media/", f"{images_folder}/")
            return f'![Image]({new_src})'
        return match.group(0)

    pattern = r'!\[Image\]\((.*?)\)'
    md_text = re.sub(pattern, replace_img_src, md_text)
    return md_text


def process_all_docx_files(args):
    current_dir = os.getcwd()
    docx_files = [f for f in os.listdir(current_dir) if f.endswith(".docx")]

    if not docx_files:
        print("No.docx files found in the current directory.")
        return

    for docx_file in docx_files:
        file_path = os.path.join(current_dir, docx_file)
        print(f"Processing {file_path}...")
        process_single_file(args, file_path)


if __name__ == "__main__":
    main()